package com.spica.spicaschool.network.repository

import androidx.annotation.WorkerThread
import com.skydoves.sandwich.map
import com.skydoves.sandwich.onError
import com.skydoves.sandwich.onException
import com.skydoves.sandwich.suspendOnSuccess
import com.skydoves.whatif.whatIfNotNull
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.network.ErrorResponseMapper
import com.spica.spicaschool.network.SpicaClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import javax.inject.Inject

/**
 * 圈子 信息获取
 */
class CircleRepository
@Inject constructor(
    private val spicaClient: SpicaClient
) : Repository {

    @WorkerThread
    fun fetchDiaryList(
        pageEntity: PageEntity,
        token: String,
        type: Int,
        onStart: () -> Unit,
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) = flow {
        // val diaryList = diaryDao.queryAll()
        //获取数据
        val response =
            spicaClient.fetchCircleDiary(type, token, pageEntity.currentPage, pageEntity.pageSize)
        //获取数据成功
        response.suspendOnSuccess {
            //数据不为空
            data.whatIfNotNull { response ->
                emit(response)
            }
        }
            .onError {
                //服务器错误
                map(ErrorResponseMapper()) {
                    onError("[Code: $code]: $msg")
                }
            }
            .onException {
                //客户端错误
                onError(message)
            }
    }
        .onStart {
            //开始的回调
            onStart()
        }.onCompletion {
            //结束的回调用
            onComplete()
        }
        .flowOn(Dispatchers.IO)
}